package marcis.jarina.hibernate;

import marcis.jarina.hibernate.dao.ArchiveDao;
import marcis.jarina.hibernate.entities.Archive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ArchiveContinuousSaver implements ContinuousSaver<Archive> {

    private List<Archive> list = new ArrayList<Archive>();

    private static final int MAX = 100;

    @Autowired
    private ArchiveDao archiveDao;

    @Override
    public void addEntity(Archive object) {
        list.add(object);
        if(isOverFlow(list)) {
            save();
            // to avoid high memory use
            list.clear();
        }
    }

    @Override
    public boolean isOverFlow(List<Archive> archives) {
        return archives.size() > MAX;
    }

    @Override
    public void save() {
        final Archive[] archivesArray = new Archive[list.size()];
        list.toArray(archivesArray);
        archiveDao.save(archivesArray);
    }

    @Override
    public List<Archive> getList() {
        return list;
    }
}
